import userBaseDao from "../dao/userbaseDB.js";
import {httpResult} from "../utils/utils.js";
import {createToken} from "../middleware/JWTToken.js";
import {
  getUserBaseInfo,
  loginGetToken,
  sendEmailToUpdatePWD,
  signNewAccount,
  updatePWD,
  updateUserBaseInfo
} from "../service/userService.js";
//注册
export const signIn = async (req, res, next) => {
  let {passwordMd5, name, email} = req.body;
  if (!passwordMd5 || !email) {
    throw new Error("账号密码邮箱不能为空！");
  }
  let account = await signNewAccount(passwordMd5, name, email);
  res.json(httpResult.success({
    msg: "注册成功！",
    account
  }));
};

//登录
export const login = async (req, res, next) => {
  let {account, passwordMd5} = req.body;
  if (!(account && passwordMd5)) {
    throw new Error("账号密码不能为空！");
  }

  let token = await loginGetToken(account, passwordMd5);

  res.json(httpResult.success({token, msg: "登录成功"}));
};

//获取新token
export const getNewToken = async (req, res, next) => {
  if (req.body.requestToGetNewToken) {
    let sender = req.headers['authorization'].split(" ")[2];
    let newToken = await createToken(sender);
    res.json(httpResult.success({token: newToken}));
    return;
  }
  res.json(httpResult.error("获取失败"));
};

//获取用户基础信息
export const getUserInfo = async (req, res, next) => {
  let {account} = req.query;
  if (!account) {
    throw new Error("请输入用户账号！");
  }

  let userBaseInfo = await getUserBaseInfo(account);
  res.json(httpResult.success({userBaseInfo, msg: "获取成功！"}));
};

//获取用户基础信息--传入用户数组
export const getUserInfoList = async (req, res, next) => {
  let {accountList, startTime} = req.body;
  if (accountList.length === 0 || !accountList) {
    throw new Error("请输入用户账号！");
  }
  startTime = startTime ?? 0;
  let userBaseInfo = await userBaseDao.getUserBaseInfoList(accountList, startTime);
  res.json(httpResult.success({userBaseInfo, msg: "获取成功！"}));
};

//发送修改密码的邮件
export const sendEmailUpdatePassword = async (req, res, next) => {
  let {account} = req.query;
  if (!account) {
    throw new Error("请输入用户账号！");
  }
  await sendEmailToUpdatePWD(account);
  res.json(httpResult.success("发送成功"));

};

//修改密码(邮箱)
export const updateUserPassword = async (req, res, next) => {
  let {account, mailCode, newPasswordMd5} = req.query;
  if (!(account && mailCode && newPasswordMd5)) {
    throw new Error('缺少参数！');
  }
  await updatePWD(account, mailCode, newPasswordMd5);
  res.json(httpResult.success("修改成功"));

};

//修改用户基础信息（type）
export const updateUserInfo = async (req, res, next) => {
  let {account, avatar, name, birth, signature} = req.query;
  if (!account) {
    throw new Error("请输入用户账号！");
  }
  await updateUserBaseInfo(account, avatar, birth, signature, name);
  res.json(httpResult.success("修改成功！"));

};

